<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智能模拟医患对话</title>
    <style>
        body{
            background-image: url("/static/assets/bk.png");
            background-repeat: no-repeat;
            background-size: cover;
        }
        h1{
            text-align: center;
            color:aliceblue;
        }
        #chat-box {
            max-height: 70%;
            overflow-y: auto;
            width: 60%;
            margin: auto;
            margin-left: 250px;
            margin-bottom: 20px;
            padding:10px 2% 10px 3%;
            border: 1px solid #003b8f;
            border-radius: 5px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            background-color:rgba(240, 253, 255, 0.795);
            opacity: 0.9;
            position: absolute;
            right:16%;
            top:10%;
        }
        .user-message {
            text-align: start;
            background-color: rgb(12, 47, 78);
            color:rgb(219, 248, 255);
            padding: 10px;
            margin: 0;
            border-radius: 10px;
            align-self: flex-end;
            min-width: 100px;
            max-width: calc(60% - 20px);
            word-wrap: break-word;
        }
        .assistant-a-message, .assistant-b-message {
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 10px;
            margin: 5px 0;
            position: relative;
            width: 50%;
            border-radius: 10px;
            opacity: 1;
        }
        .assistant-a-message {
            background-color:  #b3ebff;
        }
        .assistant-b-message {
            background-color: #eddaff;
        }
        .tts-btn {
            background: none;
            border: none;
            cursor: pointer;
            margin-left: 8px;
            padding: 0;
            display: flex;
            align-items: center;
        }
        .tts-btn[disabled] {
            cursor: wait;
            opacity: 0.5;
        }
        .input {
            position: absolute;
            left:18%;
            top:85%;
            display: flex;
            resize: vertical;
            overflow-y: auto;
            border: 1px solid #003b8f;
            background-color: rgba(240, 248, 255, 0.63);
            padding: 10px;
            width: 65%;
            min-height: 50px;
            font-size: 16px;
            color: #333;
        }
        #user-input{
            width: 80%;
        }
        .list {
            background-color: none;
            width: 15%;
            position: absolute;
            top:65%;
            font-weight: bold;
            font-size:large;
            font-family: "宋体", "SimHei", sans-serif;
            color: rgb(0, 0, 148);
            z-index: 99;
            opacity: 0.8;
        }
        ul{
            list-style-type: none;
        }
        li{
            background-color: rgb(12, 47, 78);
            text-align: center;
            margin-bottom:10px;
            padding-top:10px;
            height: 30px;
            border-radius: 15px;
        }
        .list ul li a {
            text-decoration: none;
            color: rgb(255, 255, 255);
            display: block;
            position: relative;
            padding-top: 10px;
            margin-bottom: 9px;
            bottom: 35%;
            height:100%;
            text-align: center; /* 文本居中 */
            border-radius: 15px;
        }
        .list ul li a:hover {
            background-color:rgb(219, 248, 255);
            color: rgb(12, 47, 78);
            border:2px solid  rgb(12, 47, 78);
        }
        .curr{
            background-color: rgb(219, 248, 255);
        }
        #send-button {
            padding: 0 30px;
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <h1>AI模拟医患对话</h1>
    <div id="content">
        <div id="chat-box">
            <div class="assistant-a-message"><span>模拟患者: 欢迎来到AI模拟对话，我将模仿不同mbti的病人来向您进行咨询。</span>
                <button class="tts-btn" data-text="欢迎来到AI模拟对话，我将模仿不同mbti的病人来向您进行咨询。" onclick="playTTS(this)">
                    <img src="data:image/svg+xml;utf8,<svg width='18' height='18' viewBox='0 0 20 20' fill='none' xmlns='http://www.w3.org/2000/svg'><path d='M2 7V13H6L11 18V2L6 7H2Z' fill='gray'/></svg>" width="18"/></button>
            </div>
            <div class="assistant-b-message"><span>医学助手: 我负责尽可能解答您在医学上的困惑。</span>
                <button class="tts-btn" data-text="我负责尽可能解答您在医学上的困惑。" onclick="playTTS(this)">
                    <img src="data:image/svg+xml;utf8,<svg width='18' height='18' viewBox='0 0 20 20' fill='none' xmlns='http://www.w3.org/2000/svg'><path d='M2 7V13H6L11 18V2L6 7H2Z' fill='gray'/></svg>" width="18"/></button>
            </div>
            <div class="assistant-a-message"><span>模拟患者: 我们准备好了。如果需要开始模拟医患对话，请选择我并输入：“请描述您的病情”</span>
                <button class="tts-btn" data-text="我们准备好了。如果需要开始模拟医患对话，请选择我并输入：请描述您的病情" onclick="playTTS(this)">
                    <img src="data:image/svg+xml;utf8,<svg width='18' height='18' viewBox='0 0 20 20' fill='none' xmlns='http://www.w3.org/2000/svg'><path d='M2 7V13H6L11 18V2L6 7H2Z' fill='gray'/></svg>" width="18"/></button>
            </div>
        </div>
        <div class="input">
            <select id="assistant-selector">
                <option value="A">模拟患者</option>
                <option value="B">医学助手</option>
            </select>
            <input type="text" id="user-input" placeholder="请输入你的问题...">
            <button id="send-button" onclick="sendMessage()">发送</button>
        </div>
        <div class="list">
            <ul>
              <li><a href="http://127.0.0.1:3001">主页</a></li>
              <li class='curr'><a href="http://127.0.0.1:5000" style="color: rgb(7, 38, 69);">模拟对话</a></li>
              <li><a href="http://127.0.0.1:3002">能力测试</a></li>
              <li><a href="http://127.0.0.1:5001">历史记录</a></li>
            </ul>
        </div>
    </div>
    <script>
        // 播放TTS音频
        function playTTS(btn) {
            const text = btn.getAttribute('data-text');
            btn.disabled = true;
            fetch('/api/tts', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({text: text})
            })
            .then(response => {
                if (!response.ok)
                    throw new Error('获取语音失败');
                return response.blob();
            })
            .then(audioBlob => {
                var audioUrl = URL.createObjectURL(audioBlob);
                var audio = new Audio(audioUrl);
                audio.play();
                audio.onended = function() {
                    btn.disabled = false;
                };
            })
            .catch(e => {
                alert('语音合成失败！');
                btn.disabled = false;
            });
        }

        function addAssistantMessage(role, content) {
            const chatBox = document.getElementById('chat-box');
            const className = role === 'A' ? 'assistant-a-message' : 'assistant-b-message';
            const prefix = role === 'A' ? '模拟患者: ' : '医学助手: ';
            // 用 span 包裹，+tts按钮
            chatBox.innerHTML += `
              <div class="${className}">
                <span>${prefix}${content}</span>
                <button class="tts-btn" data-text="${content.replace(/"/g,'')}" onclick="playTTS(this)">
                  <img src="data:image/svg+xml;utf8,<svg width='18' height='18' viewBox='0 0 20 20' fill='none' xmlns='http://www.w3.org/2000/svg'><path d='M2 7V13H6L11 18V2L6 7H2Z' fill='gray'/></svg>" width="18"/>
                </button>
              </div>
            `;
            scrollToBottom(chatBox);
        }

        function sendToAssistantA(message) {
            const chatBox = document.getElementById('chat-box');
            chatBox.innerHTML += `<div class="user-message">${message}</div>`;
            scrollToBottom(chatBox);

            fetch("/", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `user_message=${encodeURIComponent(message)}&assistant_type=A`
            })
            .then(response => {
                if (!response.ok)
                    throw new Error("Network response was not ok");
                return response.json();
            })
            .then(data => {
                const assistantResponse = data.response;
                addAssistantMessage('A', assistantResponse);
            })
            .catch(error => console.error("Error:", error));
        }

        function sendToAssistantB(message) {
            const chatBox = document.getElementById('chat-box');
            chatBox.innerHTML += `<div class="user-message">${message}</div>`;
            scrollToBottom(chatBox);

            fetch("/", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `user_message=${encodeURIComponent(message)}&assistant_type=B`
            })
            .then(response => {
                if (!response.ok)
                    throw new Error("Network response was not ok");
                return response.json();
            })
            .then(data => {
                const assistantResponse = data.response;
                addAssistantMessage('B', assistantResponse);
            })
            .catch(error => console.error("Error:", error));
        }

        function sendMessage() {
            const inputElement = document.getElementById('user-input');
            const message = inputElement.value.trim();
            const assistantSelector = document.getElementById('assistant-selector');
            if (message !== '') {
                if (assistantSelector.value === 'A') {
                    sendToAssistantA(message);
                } else {
                    sendToAssistantB(message);
                }
                inputElement.value = '';
            }
        }

        function scrollToBottom(element) {
            element.scrollTop = element.scrollHeight;
        }

        var inputField = document.getElementById("user-input");
        inputField.addEventListener('keydown', function(event) {
            if (event.key === "Enter") {
                event.preventDefault();
                sendMessage();
            }
        });
    </script>
</body>
</html>